//
//  Hear_AnswerScrollViewController.m
//  Hear
//
//  Created by mac on 2018/5/7.
//  Copyright © 2018年 mac. All rights reserved.
//  回答列表

#import "Hear_AnswerScrollViewController.h"

#import "Hear_PhonographView.h" // 推荐view
#import "Hear_BaseModel.h" // 基础model

#import "Hear_AnswerViewController.h" // 回答话题

#import "HRDynamicViewController.h" // 个人主页

#import "HRUMShareTool.h" // 分享

#import "HRFollowDyanmicInfoViewController.h" // 详情

#import "Track.h"
#import "DOUAudioStreamer.h"

@interface Hear_AnswerScrollViewController () <UIScrollViewDelegate>

/** 底层scrollview */
@property (nonatomic, strong) UIScrollView *rootScroll;

@property (nonatomic, strong) NSMutableDictionary *param;
@property (nonatomic, assign) int page;

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *dataSource;

/** 存储点击状态 */
@property (nonatomic, strong) NSMutableArray *clickType;

/** 数据总数 */
@property (nonatomic, assign) NSInteger totalcount;

#pragma mark 播放器
/** 播放器 */
@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) AVPlayerItem *item;

@property (nonatomic, strong) DOUAudioStreamer *streamer;

/** 播放失败的音频文件 */
@property (nonatomic, copy) NSString *videoStr;

@end

@implementation Hear_AnswerScrollViewController

#pragma mark Set
- (NSMutableDictionary *)param {
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)clickType {
    if (!_clickType) {
        _clickType = [NSMutableArray array];
    }
    return _clickType;
}

#pragma mark loadview
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    
    Hear_PhonographView *currentView = self.rootScroll.subviews[0];
    [currentView.rotatingImg resumeRotate];
    
    [self.player play];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
    
    [self.player pause];
    [self.streamer pause];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"回答列表";
    
    [self creatDefaultParam];
    
    [self registerNotification];
    
}

- (void)registerNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographAnswerAction:) name:@"Hear_PhonographAnswer" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographPlayAction:) name:@"Hear_PhonographPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographRotatingImgAction:) name:@"Hear_PhonographRotatingImg" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographHeaderTapAction:) name:@"Hear_PhonographHeaderTap" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographCommentAction:) name:@"Hear_PhonographComment" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographRotatingTapAction:) name:@"Hear_PhonographRotatingTap" object:nil];
}

#pragma mark 请求数据
- (void)creatDefaultParam {
    self.page = 0;
    [self.param setObject:[NSString stringWithFormat:@"%d", self.page] forKey:@"PageIndex"];
    [self.param setObject:[NSString stringWithFormat:@"%d", 10] forKey:@"PageSize"];
    [self.param setObject:USERID forKey:@"CurrentUserLocalId"];
    [self.param setObject:self.QuestionID forKey:@"QuestionId"];
    [self getDataByQuestionID];
}

- (void)getDataByQuestionID {
    
    YTKApi *api = [YTKApi apiGetWithUrl:@"SoundInfo/Get_GetSoundByQuestionId" para:self.param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                
                NSString *jsonStr = dict[@"BodyContent"];
                
                NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
                NSError *err;
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:&err];
                if(err) {
                    if ([dict[@"Message"] isEqualToString:@"暂无数据"]) {
                        [self showMessage:@"暂无更多数据" atPosition:ShowPosition_Bottom];
                    }
                } else {
                    Hear_BaseModel *baseModel = [Hear_BaseModel modelWithDictionary:dic];
                    self.totalcount = baseModel.TotalCount;
                    
                    for (Hear_PhonographRecommendModel *model in baseModel.List) {
                        [self.dataSource addObject:model];
                    }
                    
                    for (int i = 0; i < self.dataSource.count; i++) {
                        [self.clickType addObject:@NO];
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if (self.page == 0) {
                            [self creatMainView];
                        } else {
                            [self addScrollviewSize];
                        }
                        
                        // 给第一个界面赋值
                        Hear_PhonographView *currentView = self.rootScroll.subviews[0];
                        
                        currentView.model = self.dataSource[0];
                        
                        [self creatPlayerByModel:self.dataSource[0]];
                        [currentView.rotatingImg resumeRotate];
                        [self.player play];
                        
                    });
                }
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}

#pragma mark 界面
- (void)creatMainView {
    
    CGFloat height = ScreenHeight - kTopHeight;
    
    UIScrollView *rootScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, height)];
    rootScroll.showsVerticalScrollIndicator = false;
    rootScroll.showsHorizontalScrollIndicator = false;
    rootScroll.pagingEnabled = YES;
    rootScroll.delegate = self;
    
    self.rootScroll = rootScroll;
    self.rootScroll.contentSize = CGSizeMake(ScreenWidth, height * self.dataSource.count);
    
    [self.view addSubview:rootScroll];
    
    for (int i = 0; i < self.dataSource.count; i++) {
        Hear_PhonographView *view = [[Hear_PhonographView alloc] initWithFrame:CGRectMake(0, height * i, ScreenWidth, height)];
        
        [self.rootScroll addSubview:view];
    }
}

- (void)addScrollviewSize {
    
    CGFloat height = ScreenHeight - kTopHeight;
    
    NSInteger datacount = self.dataSource.count;
    NSInteger viewcount = self.rootScroll.subviews.count;
    
    Hear_PhonographView *lastview = (Hear_PhonographView *)self.rootScroll.subviews.lastObject;
    
    self.rootScroll.contentSize = CGSizeMake(ScreenWidth, self.dataSource.count * height);
    
    for (int i = 0; i < datacount - viewcount; i++) {
        Hear_PhonographView *view = [[Hear_PhonographView alloc] initWithFrame:CGRectMake(0, lastview.bottom + height * i, ScreenWidth, height)];
        [self.rootScroll addSubview:view];
    }
    
}

#pragma mark 界面数据展示
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == self.rootScroll) {
        
        NSInteger index = scrollView.contentOffset.y / self.rootScroll.frame.size.height;
        
        Hear_PhonographView *currentView = scrollView.subviews[index];
        
        currentView.model = self.dataSource[index];
        
        [self creatPlayerByModel:currentView.model];
        
        if ([self.clickType[index] isEqual:@NO]) {
            [self.player play];
            [currentView.rotatingImg resumeRotate];
        } else {
            [self.player pause];
            [currentView.rotatingImg stopRotating];
        }
        
        if (self.totalcount <= 10 && index == self.totalcount - 1) {
            [self showMessage:@"已经到底了!" atPosition:ShowPosition_Bottom];
        } else {
            if (index != 0 && (index + 1) % 10 == 0) {
                self.page += 1;
                [self.param setObject:[NSString stringWithFormat:@"%d", self.page] forKey:@"PageIndex"];
                [self.param setObject:[NSString stringWithFormat:@"%d", 10] forKey:@"PageSize"];
                [self.param setObject:USERID forKey:@"CurrentUserLocalId"];
                [self.param setObject:USERID forKey:@"QuestionId"];
                [self getDataByQuestionID];
            }
        }
        
    }
    
}

#pragma mark >>>>>>>>>>>>>>播放器<<<<<<<<<<<<<<
- (void)creatPlayerByModel:(Hear_PhonographRecommendModel *)model {
    
    [self.item removeObserver:self forKeyPath:@"status"];
    
    self.videoStr = model.SoundUrl;
    
    self.item = [[AVPlayerItem alloc] initWithURL:GetUrlWithStr(model.SoundUrl)];
    
    [self.item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.item];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (object == self.player.currentItem) {
        if ([keyPath isEqualToString:@"status"]) {
            
            if (self.player.currentItem.status == AVPlayerItemStatusReadyToPlay){
                
                [_streamer pause];
                
            } else if (self.player.currentItem.status == AVPlayerItemStatusFailed) {
                
                Track *track = [[Track alloc] init];
                track.audioFileURL = [NSURL URLWithString:self.videoStr];
                
                _streamer = nil;
                _streamer = [DOUAudioStreamer streamerWithAudioFile:track];
                
                [_streamer play];
                
            }
            
        }
    }
}

#pragma mark 回答话题
- (void)Hear_PhonographAnswerAction:(NSNotification *)sender {
    Hear_PhonographRecommendModel *model = sender.object;
    
    Hear_AnswerViewController *vc = [Hear_AnswerViewController new];
    
    vc.model = model;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 播放话题
- (void)Hear_PhonographPlayAction:(NSNotification *)sender {
    UIButton *playbtn = sender.object;
    
    NSInteger index = self.rootScroll.contentOffset.y / self.rootScroll.frame.size.height;
    
    // 播放中,默认进入自动播放
    if ([self.clickType[index] isEqual:@NO]) {
        
        [self.clickType replaceObjectAtIndex:index withObject:@YES];
        
        [playbtn setImage:GetImgWithStr(@"Phonograph_play") forState:UIControlStateNormal];
        
        [self.player pause];
        
        [self.streamer pause];
        
    } else {
        
        [self.clickType replaceObjectAtIndex:index withObject:@NO];
        
        playbtn.hidden = YES;
        
        [self.player play];
        
        [self.streamer play];
        
    }

}

- (void)Hear_PhonographRotatingImgAction:(NSNotification *)sender {
    UIImageView *img = sender.object;
    
    NSInteger index = self.rootScroll.contentOffset.y / self.rootScroll.frame.size.height;
    if ([self.clickType[index] isEqual:@NO]) {
        [img resumeRotate];
    } else {
        [img stopRotating];
    }
}

#pragma mark 题主头像点击
- (void)Hear_PhonographHeaderTapAction:(NSNotification *)sender {
    
    [self.player pause];
    [self.streamer pause];
    
    Hear_PhonographRecommendModel *model = sender.object;
    
    [MobClick event:@"Hearer8"];
    HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
    
    dynamicVC.currentUserID = model.MasterUserLocalId;
    [self.navigationController pushViewController:dynamicVC animated:YES];
}

#pragma mark 评论事件
- (void)Hear_PhonographCommentAction:(NSNotification *)sender {
    Hear_PhonographRecommendModel *model = sender.object;
    
    HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
    infoVC.dynamicID = model.LocalId;
    [self.navigationController pushViewController:infoVC animated:YES];
}

#pragma mark 转动头像点击
- (void)Hear_PhonographRotatingTapAction:(NSNotification *)sender {
    
    [self.player pause];
    [self.streamer pause];
    
    Hear_PhonographRecommendModel *model = sender.object;
    
    [MobClick event:@"Hearer8"];
    HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
    
    dynamicVC.currentUserID = model.UserLocalId;
    [self.navigationController pushViewController:dynamicVC animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.item removeObserver:self forKeyPath:@"status"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
